﻿package com.agileai.miscdp.util;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.XPath;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.osgi.framework.Bundle;

import com.agileai.common.IniReader;
import com.agileai.domain.KeyNamePair;
import com.agileai.miscdp.DeveloperConst;
import com.agileai.miscdp.DeveloperConst.FuncTreeXml;
import com.agileai.miscdp.MiscdpPlugin;
import com.agileai.miscdp.hotweb.database.DBManager;
import com.agileai.miscdp.hotweb.database.DBManager.DataBaseType;
import com.agileai.miscdp.hotweb.domain.Column;
import com.agileai.miscdp.hotweb.domain.FuncProject;
import com.agileai.miscdp.hotweb.domain.ListTabColumn;
import com.agileai.miscdp.hotweb.domain.PageFormField;
import com.agileai.miscdp.hotweb.domain.ProjectConfig;
import com.agileai.miscdp.hotweb.domain.Validation;
import com.agileai.miscdp.hotweb.ui.views.TreeObject;
import com.agileai.miscdp.server.HotServerManage;
import com.agileai.miscdp.server.HotServerManageService;
import com.agileai.util.StringUtil;
import com.agileai.util.XmlUtil;

/**
 * Miscdp通用辅助类
 */
abstract public class MiscdpUtil {
	private static final String NEWLINE = "\r\n";
	private static IniReader iniReader = null;

	@SuppressWarnings({"rawtypes" })
	private static Map map;

	private static HashMap<String,HotServerManage> stubCache = new HashMap<String,HotServerManage>();
	
	public static synchronized HotServerManage getHotServerManage(String appName){
		ProjectConfig projectConfig = getProjectConfig(appName);
		String serverAddress = projectConfig.getServerAddress();
		String serverPort = projectConfig.getServerPort();
		String wsdlURL = "http://"+serverAddress+":"+serverPort+"/HotServer/services/HotServerManage?wsdl";
		HotServerManage result = null;
		if (!stubCache.containsKey(wsdlURL)){
			URL wsdlLocation = null;
			try {
				wsdlLocation = new URL(wsdlURL);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
			HotServerManageService hotServerManageService = new HotServerManageService(wsdlLocation);
			result = hotServerManageService.getHotServerManagePort();
			stubCache.put(wsdlURL, result);
		}else{
			result = stubCache.get(wsdlURL);
		}
		return result;
	}
    
	public static String getJvmbit(){
    	String result = "32";
    	String osarch = System.getProperty("os.arch");
    	if (osarch.contains("64")){
    		result = "64";
    	}
    	return result;
    }
    
	public static synchronized HotServerManage getHotServerManage(String serverAddress,String serverPort){
		String wsdlURL = "http://"+serverAddress+":"+serverPort+"/HotServer/services/HotServerManage?wsdl";
		HotServerManage result = null;
		if (!stubCache.containsKey(wsdlURL)){
			URL wsdlLocation = null;
			try {
				wsdlLocation = new URL(wsdlURL);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
			HotServerManageService hotServerManageService = new HotServerManageService(wsdlLocation);
			result = hotServerManageService.getHotServerManagePort();
			stubCache.put(wsdlURL, result);
		}else{
			result = stubCache.get(wsdlURL);
		}
		return result;
	}
	
	public static String getValidName(String name){
		StringBuffer result = new StringBuffer();
		String[] nameArray = name.split("_");
		for (int i=0;i < nameArray.length;i++){
			String temp = nameArray[i].toLowerCase();
			result.append(temp.substring(0,1).toUpperCase());
			if (temp.length() > 1){
				result.append(temp.substring(1,temp.length()));
			}
		}
		return result.toString();
	}
	public static IEditorPart openEditor(IWorkbenchPage page,FuncProject funcProject){
		IEditorPart editor = null;
		boolean flags = false;
		IEditorReference[] editors = page.getEditorReferences();
		for (int i = 0; i < editors.length; i++) {
			String oldTitleToolTip = editors[i].getTitleToolTip();
			if (funcProject.getProjectName().equals(oldTitleToolTip)) {
				flags = true;
				editor = editors[i].getEditor(true);
				break;
			}
		}
		if (flags) {
			page.bringToTop(editor);
		} else {
			try {
				editor = page.openEditor(funcProject,funcProject.getEditorId());
			} catch (PartInitException e) {
				e.printStackTrace();
			}
		}
		return editor;
	}	
	public static boolean isContainChinese(String value){
		return !(value.getBytes().length == value.length());
	}
	public static ListTabColumn retrieveMachedListTabColumn(List<ListTabColumn> listTabColumns,String property){
		ListTabColumn result = null;
		for (int i=0;i < listTabColumns.size();i++){
			ListTabColumn listTabColumn = listTabColumns.get(i);
			if (property.equals(listTabColumn.getProperty())){
				result = listTabColumn;
				break;
			}
		}
		return result;
	}
	public static void syncListGrid2FormField(List<ListTabColumn> listTabColumns,List<PageFormField> pageFormFields){
		for (int i=0;i < pageFormFields.size();i++){
			PageFormField pageFormField = pageFormFields.get(i);
			String filedCode = pageFormField.getCode();
			ListTabColumn listTabColumn= retrieveMachedListTabColumn(listTabColumns, filedCode);
			if (listTabColumn == null){
				continue;
			}
			String label = listTabColumn.getTitle();
			if (MiscdpUtil.isContainChinese(label)){
				pageFormField.setLabel(label);
			}
			String mappingItemp = listTabColumn.getMappingItem();
			if (!StringUtil.isNullOrEmpty(mappingItemp)){
				pageFormField.setTagType(PageFormField.SELECT_TAG);
				pageFormField.setValueProvider(mappingItemp);
			}
		}
	}	
	public static void syncListLabel2FormField(List<ListTabColumn> listTabColumns,List<PageFormField> pageFormFields){
		for (int i=0;i < pageFormFields.size();i++){
			PageFormField pageFormField = pageFormFields.get(i);
			String filedCode = pageFormField.getCode();
			ListTabColumn listTabColumn= retrieveMachedListTabColumn(listTabColumns, filedCode);
			if (listTabColumn == null){
				continue;
			}
			String label = listTabColumn.getTitle();
			if (MiscdpUtil.isContainChinese(label)){
				pageFormField.setLabel(label);
			}
		}
	}
	public static IProject getProject(String projectName){
		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
		return project;
	}
	public static String getDefaultSqlMapPath(String projectName){
		String result = getProject(projectName).getLocation().toString()+"/src/sqlmap";
		return result;
	}
	public static String getCfgFileName(String projectName,String fileNameKey){
		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
		IFile file = project.getFile(new Path("/"+fileNameKey));
		String projPath = project.getLocation().toFile().getAbsolutePath();
		String fileName = projPath + File.separator+ file.getName();
		return fileName;
	}
    public static ProjectConfig getProjectConfig(String appName){
		ProjectConfig projectConfig = new ProjectConfig();
		String configFile = MiscdpUtil.getCfgFileName(appName,DeveloperConst.PROJECT_CFG_NAME);
		projectConfig.setConfigFile(configFile);
		projectConfig.initConfig();
		return projectConfig;
    }
    public static void updateProjectConfig(String projectName,String serverPort){
		String xmlFile = MiscdpUtil.getCfgFileName(projectName,DeveloperConst.PROJECT_CFG_NAME);
		Document document = XmlUtil.readDocument(xmlFile);
		String serverPortNodePath = "//HotwebModule/ServerConfig/ServerPort";
		Element serverPortNode = (Element)document.selectSingleNode(serverPortNodePath);
		if (serverPortNode != null){
			serverPortNode.setText(serverPort);
		}
		XmlUtil.writeDocument(document, "utf-8", xmlFile);
    }
	public static void updateTreeIndexFile(TreeObject projectTreeObject){
		String projectName = projectTreeObject.getProjectName();
		String xmlFile = MiscdpUtil.getCfgFileName(projectName,DeveloperConst.PROJECT_CFG_NAME);
		Document document = XmlUtil.readDocument(xmlFile);
		Element funcTreeElement = document.getRootElement().element("FuncTree");
		if (funcTreeElement != null){
			funcTreeElement.detach();
			document.remove(funcTreeElement);
		}
		Element element = document.getRootElement().addElement("FuncTree");
		MiscdpUtil.buildTreeDocument(element, projectTreeObject);
		XmlUtil.writeDocument(document, "utf-8", xmlFile);
	}
	
	public static String getFuncFileName(String projectName,String funcId){
		IProject project = getProject(projectName);
		String projPath = project.getLocation().toFile().getAbsolutePath();
		String fileName = projPath + File.separator+ FuncTreeXml.DIR_NAME + File.separator + funcId + ".xml";
		File tempFile = new File(fileName);
		File parentFile = tempFile.getParentFile();
		if (!parentFile.exists()){
			parentFile.mkdirs();
		}
		return fileName;
	}
	
	public static IniReader getIniReader(){
		if (iniReader == null){
			String filename = "resource/config.ini";
			try {
				String fullFileName = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource(filename)).getFile().toString();
				iniReader = new IniReader(fullFileName);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return iniReader;
	}
	public static String[] getDriverJarArray(String databaseType){
		String driverPath = MiscdpUtil.getDriverJars(getDriverJarList(databaseType));
		String[] driverJarPaths = driverPath.split(";");
		String[] driverJars = new String[driverJarPaths.length];
		for (int i=0;i < driverJarPaths.length;i++){
			String temp = driverJarPaths[i];
			driverJars[i] = temp;	
		}
		return driverJars;
	}
	private static java.util.List<String> getDriverJarList(String databaseType) {
		List<String> driverJarList = new ArrayList<String>();
		String driverJarPath = MiscdpUtil.getDriverPath(databaseType);
		driverJarList.add(driverJarPath);
		return driverJarList;
	}
	public static String getDriverPath(String databaseType){
		String result = null;
		try {
			String fileName = null;
			if (DataBaseType.MySQL.equals(databaseType)){
				fileName = "resource/libs/mysql-connector-java-5.1.22-bin.jar";
			}else if (DataBaseType.Oracle.equals(databaseType)){
				fileName = "resource/libs/ojdbc14.jar";
			}else if (DataBaseType.SQLServer.equals(databaseType)){
				fileName = "resource/libs/jtds-1.2.7.jar";
			}
			Bundle bundle = Platform.getBundle(MiscdpPlugin.getPluginId());
			URL url = bundle.getResource(fileName);
			result = FileLocator.toFileURL(url).getFile().toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	private static String getDriverJars(java.util.List<String> list){
		String result = "";
		if (list != null){
			StringBuffer temp = new StringBuffer();
			for (int i=0;i < list.size();i++){
				temp.append(list.get(i));
				if (i < list.size()-1){
					temp.append(";");
				}
			}
			result = temp.toString();
		}
		return result;
	}
	public static boolean isValidConnection(String driverClass,String driverUrl,String userId,String userPwd,String[] driverJars){
		boolean result = false;
		DBManager dbManager = DBManager.getDefInstance();

		dbManager.setDriverClass(driverClass);
		dbManager.setDriverUrl(driverUrl);
		dbManager.setUserId(userId);
		dbManager.setUserPwd(userPwd);
		for (int i=0;i < driverJars.length;i++){
			String temp = driverJars[i];
			dbManager.getDriverJars().add(MiscdpUtil.toURL(temp));	
		}
		Connection connection = dbManager.createConnection();
		if (connection == null){
			result = false;
		}
		else{
			result = true;
			dbManager.releaseConnection(connection);
		}
		return result;
	}
	
	public static File getInitSQLFile(String databaseType){
		File result = null;
		try {
			String fileName = null;
			if (DataBaseType.MySQL.equals(databaseType)){
				fileName = "resource/sqls/mysql.sql";
			}else if (DataBaseType.Oracle.equals(databaseType)){
				fileName = "resource/sqls/oracle.sql";
			}else if (DataBaseType.SQLServer.equals(databaseType)){
				fileName = "resource/sqls/sqlserver.sql";
			}			
			String fullFilePath = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource(fileName)).getFile().toString();			
			result = new File(fullFilePath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}	
	
	public static JavaFormater getJavaFormater(){
		return new JavaFormater();
	}
	
	public static URL toURL(String fileName){
		URL result = null;
		try {
			result = new File(fileName).toURI().toURL();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public static String parseDataBaseType(String databaseURL){
		String result = DataBaseType.MySQL;
		if (databaseURL.toLowerCase().indexOf("oracle") > -1){
			result = DataBaseType.Oracle;
		}
		else if (databaseURL.toLowerCase().indexOf("sqlserver") > -1){
			result = DataBaseType.SQLServer;
		}
		return result;
	}
	
	public static void buildTreeDocument(Element funcTreeElement,TreeObject parentTreeObject){
		TreeObject [] treeContents = parentTreeObject.getChildren();
		for (int i=0;i < treeContents.length;i++){
			TreeObject treeObject = treeContents[i];
			String id = treeObject.getId();
			String name = treeObject.getName();
			String nodeType = treeObject.getNodeType();
			if (TreeObject.NODE_COMPOSITE.equals(nodeType)){
				Element funcListElement = funcTreeElement.addElement("FuncList");
				funcListElement.addAttribute(FuncTreeXml.ID,id);
				funcListElement.addAttribute(FuncTreeXml.NAME,name);
				buildTreeDocument(funcListElement,treeObject);
			}
			else {
				String funcType = treeObject.getFuncType();
				String funcTypeName = treeObject.getFuncTypeName();
				String funcSubPkg = treeObject.getFuncSubPkg();
				Element funcNodeElement = funcTreeElement.addElement("FuncNode");
				funcNodeElement.addAttribute(FuncTreeXml.ID,id);
				funcNodeElement.addAttribute(FuncTreeXml.NAME,name);
				funcNodeElement.addAttribute(FuncTreeXml.SUBPKG,funcSubPkg);
				funcNodeElement.addAttribute(FuncTreeXml.TYPE,funcType);
				funcNodeElement.addAttribute(FuncTreeXml.TYPE_NAME,funcTypeName);
			}
		}
	}
	public static URL[] toURL(String[] fileNames){
		int length = fileNames.length;
		URL[] result = new URL[length];
		for (int i=0;i < length;i++){
			String fileName = fileNames[i];
			result[i] = toURL(fileName);
		}
		return result;
	}
	public static String toString(String[] stringArray,String spliter){
		StringBuffer result = new StringBuffer();
		for (int i=0;i < stringArray.length;i++){
			result.append(stringArray[i]).append(spliter);
		}
		return result.toString();
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static List toList(Object[] objects){
		List list = new ArrayList();
		for (int i=0;i < objects.length;i++){
			list.add(objects[i]);
		}
		return list;
	}
	public static String getDataType(String sqlClassName){
		if (map == null){
			IniReader reader = MiscdpUtil.getIniReader();
			map = reader.getProperties("DataTypeMapping");
		}
		String result = "other";
		if (map.containsKey(sqlClassName)){
			result = String.valueOf(map.get(sqlClassName));
		}
		return result;
	}
	public static String getProcessedConditionSQL(String sql){
		List<String> sharpParams = getSharpParams(sql);
		List<String> dolarParams = getDolarParams(sql);
		List<String> sharpParamSegments = getSharpParamSegments(sql);
		List<String> dolarParamSegments = getDolarParamSegments(sql);
		
		if (sharpParams.size() == sharpParamSegments.size() && sharpParamSegments.size() > 0){
			for (int i=0;i < sharpParams.size();i++){
				String searchString = sharpParamSegments.get(i);
				String newSearchString = processSearchString(searchString);
				String sharpParam = sharpParams.get(i);
				String replacement = "<isNotEmpty prepend=\" \" property=\"" + sharpParam+"\">"+NEWLINE
						+ newSearchString+NEWLINE
						+"</isNotEmpty>";
				sql = StringUtils.replace(sql, searchString, replacement);	
			}
		}
		if (dolarParams.size() == dolarParamSegments.size() && dolarParamSegments.size() > 0){
			for (int i=0;i < dolarParams.size();i++){
				String searchString = dolarParamSegments.get(i);
				String newSearchString = processSearchString(searchString);
				String dolarParam = dolarParams.get(i);
				String replacement = "<isNotEmpty prepend=\" \" property=\"" + dolarParam+"\">"+NEWLINE
						+ newSearchString+NEWLINE
						+"</isNotEmpty>";
				sql = StringUtils.replace(sql, searchString, replacement);	
			}
		}
		return sql;
	}
	private static String processSearchString(String searchString){
		String result = searchString.replaceAll(">","&gt;");
		result = result.replaceAll("<", "&lt;"); 
		return result;
	}
    @SuppressWarnings({"rawtypes" })
	public static List getParams(String sql) {
    	List<String> params = new ArrayList<String>();
    	List<String> sharpParams = getSharpParams(sql);
    	List<String> dolarParams = getDolarParams(sql);
    	params.addAll(sharpParams);
    	params.addAll(dolarParams);
    	return params;
    }
    private static List<String> getSharpParams(String sql){
    	List<String> params = new ArrayList<String>();
    	int initIndex = 1;
    	while(StringUtils.indexOf(sql,"#",initIndex) > 1){
    		int sIndex = StringUtils.indexOf(sql, "#", initIndex);
        	int eIndex = StringUtils.indexOf(sql, "#", sIndex+1);
        	if (eIndex > sql.length()){
        		break;
        	}
        	String param = sql.substring(sIndex+1,eIndex);
        	params.add(param);
        	initIndex = eIndex+1;
        	if (initIndex > sql.length()){
        		break;
        	}
    	}	
    	return params;
    }
    private static List<String> getDolarParams(String sql){
    	List<String> params = new ArrayList<String>();
    	int initIndex = 1;
    	while(StringUtils.indexOf(sql,"$",initIndex) > 1){
    		int sIndex = StringUtils.indexOf(sql, "$", initIndex);
        	int eIndex = StringUtils.indexOf(sql, "$", sIndex+1);
        	if (eIndex > sql.length()){
        		break;
        	}
        	String param = sql.substring(sIndex+1,eIndex);
        	params.add(param);
        	initIndex = eIndex+1;
        	if (initIndex > sql.length()){
        		break;
        	}
    	}    	
    	return params;
    }
    private static List<String> getSharpParamSegments(String sql){
    	List<String> params = new ArrayList<String>();
    	String tempSql = sql.toLowerCase();
    	int initIndex = 1;
    	while(StringUtils.indexOf(sql,"#",initIndex) > 1){
    		int sIndex = StringUtils.indexOf(sql, "#", initIndex);
        	int eIndex = StringUtils.indexOf(sql, "#", sIndex+1);
        	if (eIndex > sql.length()){
        		break;
        	}
        	int andStartIndex = StringUtils.lastIndexOf(tempSql,"and ",eIndex);
        	String param = sql.substring(andStartIndex,eIndex+1);
        	params.add(param);
        	initIndex = eIndex+1;
        	if (initIndex > sql.length()){
        		break;
        	}
    	}	
    	return params;
    }
    private static List<String> getDolarParamSegments(String sql){
    	List<String> params = new ArrayList<String>();
    	String tempSql = sql.toLowerCase();
    	int initIndex = 1;
    	while(StringUtils.indexOf(sql,"$",initIndex) > 1){
    		int sIndex = StringUtils.indexOf(sql, "$", initIndex);
        	int eIndex = StringUtils.indexOf(sql, "$", sIndex+1);
        	if (eIndex > sql.length()){
        		break;
        	}
        	int andStartIndex = StringUtils.lastIndexOf(tempSql,"and ",eIndex);
        	
        	int dolarValidEndIndex = 0;
        	int dolarValidEndIndex0 = StringUtils.indexOf(sql, " ",eIndex);
        	int dolarValidEndIndex1 = StringUtils.indexOf(sql, NEWLINE,eIndex);
        	
        	if (dolarValidEndIndex1 < dolarValidEndIndex0 && dolarValidEndIndex1 > 0){
        		dolarValidEndIndex = dolarValidEndIndex1;
        	}else{
        		dolarValidEndIndex = dolarValidEndIndex0;
        	}
        	
        	if (dolarValidEndIndex < 0){
        		dolarValidEndIndex = sql.length();
        	}
        	
        	String param = sql.substring(andStartIndex,dolarValidEndIndex);
        	params.add(param);
        	initIndex = eIndex+1;
        	if (initIndex > sql.length()){
        		break;
        	}
    	}    	
    	return params;
    }
    
	public static String[] getColNames(List<PageFormField> pageFormFieldList){
		String[] result = null;
		if (pageFormFieldList != null && pageFormFieldList.size() > 0){
			int count = pageFormFieldList.size();
			result = new String[count];
			for (int i=0;i < count;i++){
				PageFormField pageFormField = pageFormFieldList.get(i);
				result[i] = pageFormField.getCode();
			}
		}
		else{
			result = new String[0];
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public static List<String> getHandlerIdList(String projectName){
		List<String> result = new ArrayList<String>();
		String handlerXML = getProject(projectName).getLocation().toString()+"/src/HandlerContext.xml";
		Document document = XmlUtil.readDocument(handlerXML);
		String handlerPath = "//beans/bean";
		List<Element> handlerElements = document.selectNodes(handlerPath);
		for (int i=0;i < handlerElements.size();i++){
			Element element = handlerElements.get(i);
			String handlerId = element.attributeValue("id");
			result.add(handlerId);
		}
		return result;
	}
	
    public static String[] getColNames(DBManager dbManager,String tableName){
    	Column[] columns = dbManager.getColumns(tableName);
    	String[] result = new String[columns.length];
    	for (int i=0;i < columns.length;i++){
    		result[i] = columns[i].getName();
    	}
    	return result;
    }
	@SuppressWarnings({"rawtypes" })
	public static String getValidation(List validations){
		String result = "";
		if (validations != null){
			StringBuffer temp = new StringBuffer();
			for (int i=0;i < validations.size();i++){
				Validation validation = (Validation)validations.get(i);
//				temp.append(validation.getKey());
				temp.append(validation.getValue());
				if (i < validations.size()-1){
					temp.append(",");
				}
			}
			result = temp.toString(); 			
		}
		return result;
	}
	@SuppressWarnings("rawtypes")
	public static String getValidationText(String key){
		String result = "";
		IniReader reader = MiscdpUtil.getIniReader();
		List defValueList = reader.getList("Validation");
		for (int i=0;i < defValueList.size();i++){
			KeyNamePair keyNamePair = (KeyNamePair)defValueList.get(i);
			if (keyNamePair.getKey().equals(key)){
				result = keyNamePair.getValue();
				break;
			}
		}
		return result;
	}
	public static List<KeyNamePair> buildKeyNamePairList(String[] keys){
		List<KeyNamePair> result = new ArrayList<KeyNamePair>();
		for (int i=0;i < keys.length;i++){
			KeyNamePair keyNamePair = new KeyNamePair();
			String key = keys[i];
			keyNamePair.setKey(key);
			keyNamePair.setValue(key);
			result.add(keyNamePair);
		}
		return result;
	}
	public static String[] buildKeyArray(List<KeyNamePair> keyNamePairList){
		int count = keyNamePairList.size();
		String[] result = new String[count];
		for (int i=0;i < count;i++){
			KeyNamePair keyNamePair = keyNamePairList.get(i);
			result[i] = keyNamePair.getKey();
		}
		return result;
	}
	
	public static void newHandlerConfigElement(Document document,String handlerId
			,String handlerClass,String page){
        XPath xpath = document.createXPath("//beans/bean[@id='"+handlerId+"']");
        Node beanNode = xpath.selectSingleNode(document);
        if (beanNode != null){
        	beanNode.getParent().remove(beanNode);
        }
        Element beansElement = (Element)document.selectSingleNode("//beans");
        Element beanElement = beansElement.addElement("bean");
        beanElement.addAttribute("id",handlerId);
        beanElement.addAttribute("class",handlerClass);
        beanElement.addAttribute("page",page);
	}

	public static void newSqlMapConfigElement(Document document,String sqlMapFileName){
        String resourceNodePath = "//sqlMapConfig/sqlMap[@resource='sqlmap/"+sqlMapFileName+".xml']";
        Node resourceNode = document.selectSingleNode(resourceNodePath);
        if (resourceNode != null){
        	resourceNode.getParent().remove(resourceNode);
        }
    	Element sqlMapConfig = (Element)document.selectSingleNode("//sqlMapConfig");
    	Element newResElement = sqlMapConfig.addElement("sqlMap");
    	newResElement.addAttribute("resource","sqlmap/"+sqlMapFileName+".xml");
	}
	
	public static String parsePackage(String fullClassName){
		String result = null;
		int index = fullClassName.lastIndexOf(".");
		result = fullClassName.substring(0,index);
		return result;
	}
	
	public static String parseJspPath(String fullJspName){
		String result = null;
		int index = fullJspName.lastIndexOf("/");
		result = fullJspName.substring(0,index);
		return result;
	}
	
	public static String parseSqlMapPath(String sqlMapFileName){
		String result = null;
		int index = sqlMapFileName.lastIndexOf("/");
		result = sqlMapFileName.substring(0,index);
		return result;
	}
	
	public static Point getFirstMonitorSize() {
		Display display = Display.getDefault();
		if (display != null) {
			Monitor[] monitors = display.getMonitors();
			if (monitors.length == 1) {
				org.eclipse.swt.graphics.Rectangle clientArea = monitors[0].getClientArea();
				return new Point(clientArea.width / 2, clientArea.height / 2);
			}
		}
		return null;
	}
	public static void centerDialog(WizardDialog dialog){
		Point point = getFirstMonitorSize();
		Point size = dialog.getShell().getSize();
		Point centerPoint = new Point(point.x-size.x/2,point.y-size.y/2);
		dialog.getShell().setLocation(centerPoint);
	}
}